package com.example.demo.filter;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.util.IPUtils;
import com.example.demo.util.RequestDto;
import org.apache.commons.codec.digest.DigestUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;

@WebFilter(urlPatterns = "/api/sss/*", filterName = "CheckParamFilter")
public class CheckParamFilter implements Filter {

	private String md5key;

	private String whiteIps;

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		ServletRequest requestWrapper = null;
		String header = ((HttpServletRequest) request).getHeader("Content-Type");
		response.setContentType("text/html;charset=UTF-8");
		if (header == null || !"multipart/form-data".equals(header.split(";")[0])) {
			// 读取请求参数
			InputStream is = null;
			StringBuilder sb = null;
			try {
				is = request.getInputStream();
				sb = new StringBuilder();
				byte[] b = new byte[4096];
				for (int n; (n = is.read(b)) != -1;) {
					sb.append(new String(b, 0, n));
				}
			} finally {
				if (is != null) {
					is.close();
				}
			}

			// 读取到的参数字符串转成实体类
			RequestDto req = JSONObject.toJavaObject(JSONObject.parseObject(sb.toString()), RequestDto.class);

			String partner = req.getPartner(); // 项目id
			String content = req.getContent(); // 加密内容
			String key = req.getKey(); // md5秘钥
			Long timestamp = req.getTimestamp(); // 请求时间戳
			String sign = req.getSign(); // 数字签名

//			getParam(partner);// 获取IP白名单列表和验签MD5秘钥

			String ip = IPUtils.getRealIP((HttpServletRequest) request);
			if (!checkIpWhite(ip)) { // 验证IP 白名单
				response.getWriter().write(JSONObject.toJSONString("非法请求,非法的IP:"));
				return;
			}

			String signPs = DigestUtils.md5Hex(partner + content + key + timestamp + md5key); // 生成数字签名
			if (!signPs.equals(sign)) { // 验证数字签名
				response.getWriter().write(JSONObject.toJSONString("非法请求,无效的数据签名"));
				return;
			}
			requestWrapper = new CheckParamFilterRequestWrapper((HttpServletRequest) request, req); // 解密请求内容再塞回去
		}
		if (requestWrapper == null) {
			chain.doFilter(request, response);
		} else {
			chain.doFilter(requestWrapper, response);
		}

	}

	@Override
	public void destroy() {
	}

	private boolean checkIpWhite(String ip) {
		if (whiteIps != null && !"".equals(whiteIps.trim())) {
			String[] ips = whiteIps.split(",");
			for (int i = 0; i < ips.length; i++) {
				if (ip.equals(ips[i])) {
					return true;
				}
			}
		}
		return false;
	}

//	private void getParam(String partner) {
//		ConsumHqCoreApi consumHqCoreApi = SpringContextUtil.getBean(ConsumHqCoreApi.class);
//		RemoteResult result = consumHqCoreApi.selectApi(partner);
//		if ("0000".equals(result.getResultCode())) {
//			JSONObject jsonObject = (JSONObject) JSONObject.toJSON(result.getData());
//			md5key = jsonObject.getString("secretKey");
//			whiteIps = jsonObject.getString("ipList");
//		}
//
//	}

}
